/*
 *   Copyright 2012-present OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

// Packages
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import { ConnectedRouter } from 'connected-react-router';
import Cookies from 'universal-cookie';
import jwt_decode from 'jwt-decode';
import { Provider } from 'react-redux';

// Store
import store, { history } from './store';

// Actions
import { checkSession, doLogout } from './actions/sessionActions';

// Routes
import { routes } from './routes';

// Common
import PrivateRoute from './components/Common/PrivateRoute';

// Views
import { NoMatch } from './components/Views';

// Utils
import { setAuthToken, Settings } from './utils';
import { skuCELogMsg } from './utils/sku-logs';

// Styles
import '@blueprintjs/core/lib/css/blueprint.css';
import '@blueprintjs/icons/lib/css/blueprint-icons.css';
import 'antd/dist/antd.css';
import 'react-block-ui/style.css';
import './styles/app.css';

const cookies = new Cookies();
const { COOKIE_NAME } = Settings;

// Check for token
if (cookies.get(COOKIE_NAME)) {
  const jwtToken = cookies.get(COOKIE_NAME);
  const decoded = jwt_decode(jwtToken);
  const currentTime = Date.now() / 1000;

  // Set token to Auth header
  setAuthToken(jwtToken);

  if (decoded.exp < currentTime) {
    store.dispatch(doLogout());

    // Redirect to login page
    window.location.href = '/';
  } else {
    store.dispatch(checkSession());
  }
}

const App = () => {
  if (process.env.REACT_APP_STAGE === 'production') {
    skuCELogMsg();
  }

  return (
    <Provider store={store}>
      <ConnectedRouter history={history}>
        <Switch>
          {routes.map((route, index) => {
            return route.private ? (
              <PrivateRoute
                key={index}
                path={route.path}
                component={route.component}
                exact={route.exact}
              />
            ) : (
              <Route
                key={index}
                path={route.path}
                component={route.component}
                exact={route.exact}
              />
            );
          })}
          <Route component={NoMatch} />
        </Switch>
      </ConnectedRouter>
    </Provider>
  );
};

export default App;
